package com.camel.base.enums;

import com.camel.core.enums.BaseEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author Administrator
 */
@MappedJdbcTypes(JdbcType.INTEGER)
@MappedTypes({BaseEnum.class})
public class MyIntegerToEnumHandler<T> extends BaseTypeHandler<BaseEnum<T>> {
    private final Class<BaseEnum> type;

    public MyIntegerToEnumHandler(Class<BaseEnum> type) {
        this.type = type;
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, BaseEnum baseEnum, JdbcType jdbcType) throws SQLException {
        preparedStatement.setInt(i, (Integer) baseEnum.getValue());
    }

    @Override
    public BaseEnum getNullableResult(ResultSet resultSet, String s) throws SQLException {
        Integer code = resultSet.getInt(s);
        return BaseEnum.valueOfEnum(type, code);
    }

    @Override
    public BaseEnum getNullableResult(ResultSet resultSet, int i) throws SQLException {
        Integer code = resultSet.getInt(i);
        return BaseEnum.valueOfEnum(type, code);
    }

    @Override
    public BaseEnum getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        int code = callableStatement.getInt(i);
        return BaseEnum.valueOfEnum(type, code);
    }
}
